/*  

Cafechess Library: Cover basic chess programming needs, like GUI, Engine integration, 
FEN and PGN parsing.

                 \\|//
                 (o o)
--------------ooO-(_)-Ooo----------------------------------
Copyright (C) 2009  By Gregory A. Prentice Snoqualmie, WA
                    www.cafechess.org
                    cafechess@comcast.net
                      Oooo
--------------oooO----(  )---------------------------------
              (  )    (_/
               \_)

Microsoft Public License (Ms-PL)
               
Revisions:

Author        Date    Description:

*/
using System;
using System.Diagnostics;
using System.Text;

using Cafechess.Threading;
namespace Cafechess.Chess.Engines
{
  /// <summary>
  /// Retrieves the standard output from a console applications.
  /// </summary>
  public class ConsoleReader : ITextReader
  {
    Process coProcess;
    StringBuilder coBuilder;
    string [] values;
    public ConsoleReader(Process aProcess)
    {
      coProcess = aProcess;
      coBuilder = new StringBuilder();
      values = new string [1];
    }
    #region ITextReader Members

    public int FieldCount
    {
      get
      {
        return 1;
      }
    }

    public string GetName(int ndx)
    {
      string name = null;
      if( ndx == 0 )
        name = "data";
      return name;
    }

    public void GetValues(object[] objects)
    {
      if( values.Length > 0 )
        objects[0] = values[0];
      if( values.Length == 2 )
        objects[1] = values[1];
    }

    public void Open()
    {
    }
    char [] delimiter = { ' ' };
    char [] buffer = { ' ',' '};
    public bool Read()
    {      
      if(!coProcess.HasExited )
      {
        while( coProcess.StandardOutput.Read(buffer,0,1) == 1 )
        {
          if(buffer[0] == '\n' )
          {
            coBuilder.Append(buffer[0]);
            values[0] = coBuilder.ToString();
            coBuilder.Length = 0;
            break;
          }
          else if(buffer[0] == ':' )
          {
            coBuilder.Append(buffer[0]);
            values[0] = coBuilder.ToString();
            coBuilder.Length = 0;
            break;
          }
          else
          {
            coBuilder.Append(buffer[0]);
          }
          if(coProcess.HasExited )
          {
            break;
          }
        }
      }
      return !coProcess.HasExited;
    }

    public void Close()
    {
      // TODO:  Add ConsoleReader.Close implementation
    }

    #endregion
  }
}
